package com.tongcao.cn.listener.nacos;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tongcao.cn.listener.convert.PojoNacosConfigConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;

/**
 * @author:tongcao
 * @since:2019/7/26 15:45
 * Description:
 */
@Component
public class PojoNacosConfigListener {


    public static final String POJO_DATA_ID = "pojo-data-id";

    private static final Logger logger = LoggerFactory.getLogger(PojoNacosConfigListener.class);

    private Pojo pojo = new Pojo();

    @NacosInjected
    private ConfigService configService;

    @PostConstruct
    public void init() throws Exception {
        // Initialize
        pojo.setId(1L);
        pojo.setName("mercyblitz");
        pojo.setCreated(new Date());
        // Serialization
        ObjectMapper objectMapper = new ObjectMapper();
        String content = objectMapper.writeValueAsString(pojo);
        // Publish
        configService.publishConfig(POJO_DATA_ID, DEFAULT_GROUP, content);
    }

    @NacosConfigListener(dataId = POJO_DATA_ID, converter = PojoNacosConfigConverter.class)
    public void onReceived(Pojo value) throws InterruptedException {
        logger.info("onReceived(Pojo) : {}", value);
    }
}